package com.ex.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping(value="/file/")
public class FileController {
	
	@RequestMapping(value="download")
	// HttpServletResponse response 向页面中输出内容
	public String download(HttpSession session, HttpServletRequest request,  HttpServletResponse response) {

		// 1. 找到文件
		
		String fileName = (String)session.getAttribute("img");
		
		
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        
        // 告诉浏览器，当前传输的内容是1个附件文件
        response.setHeader("Content-Disposition", "attachment;fileName="
                + fileName);

		
		
		
		
		// 获取到上传文件的路径
		String path = request.getServletContext().getRealPath("upload");
		String filePath = path + File.separator + fileName;
		
		try {
			FileInputStream is = new FileInputStream(filePath);
		
			// 获取输出的对象
			ServletOutputStream os = response.getOutputStream();
			
			// 创建数组值
			byte[] b = new byte[1024];
			
			int len = 0;
			// 如果输入流中一直有内容的话，就一直读
			while( (len = is.read(b)) > 0 ) {
				os.write(b);
			}
			// 关闭http输出流
			os.close();
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "/file/upload-success.html";
	}
	
	@RequestMapping(value="upload")
	// @RequestParam MultipartFile file  说明是获取前端传递过来的文件
	public String upload(@RequestParam MultipartFile file, HttpServletRequest request) {
		
		System.out.println("upload 进来的：" + file);
		// 拿到文件 ===> 保存到服务器目录
		
		String fileName = file.getOriginalFilename();

		System.out.println("fileName: " + fileName);
		
		// 1. 服务器的根目录
		//              当前线程                                    类加载的位置                       找根路径的资源     转换为地址
		// String path = Thread.currentThread().getContextClassLoader().getResource(".").getPath();
		
		// 网站根目录
		String path = request.getServletContext().getRealPath("/");

		System.out.println("path: " + path);
		
		
		
		// 2. 创建新文件
		//      新文件路径         . File.separator 获取系统的分隔符
		//              /   linux
		//              \   windows
		// String newFilePath = path + File.separator + fileName;
		
		
		String newFilePath = path + File.separator;
		newFilePath += ("upload" + File.separator); 
		newFilePath += fileName;
		
		// 自己的文件夹路径
		
		//   创建的新的文件
		File newFile = new File(newFilePath);
		
		// 判断文件夹路径是否存在？
		File parent = newFile.getParentFile();
		if (!parent.exists()) { // 如果父文件夹不存在
			parent.mkdirs();   // 那么就创建文件夹
		}
		
		
		// 将文件转换到新文件中
		try {
			file.transferTo(newFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		System.out.println(path);
		
		
		HttpSession session = request.getSession();
		
		session.setAttribute("img", fileName);
		
		
		return "upload-success.html";
	}
	
	@ResponseBody  // 返回结果是1个json数据
	@RequestMapping("getImgName")
	public Map<String, Object> getImgName(HttpSession session) {
		
		String img = (String)session.getAttribute("img");
		
		Map<String,Object> map = new HashMap<String,Object>();
		
		map.put("img", img);
		
		return map;
	}
}
